﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using THS.HtmlHelpers;
using Veteran_cms.Models;

namespace Veteran_cms.Controllers
{
    public class ManageBlogController : BaseController
    {
        readonly Veterandb _ctx = new Veterandb();
        //
        // GET: /ManageAbout/
        const int PageSize = 6;
        public ActionResult IndexBlogs(int page = 1)
        {
            var model = new HomeAdminListViewModel();
            var blogs = _ctx.blogs.OrderByDescending(p => p.blog_id).ToList();
            model.Blogs = blogs.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.BlogPageInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = blogs.Count() };
            return View(model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Paging(int page = 1)
        {
            var model = new HomeAdminListViewModel();
            var blogs = _ctx.blogs.OrderByDescending(p => p.blog_id).ToList();
            model.Blogs = blogs.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.NewsArticlePageInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = blogs.Count() };
            return PartialView("UCBlogList", model);
        }

        public ActionResult Details(int id)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            var evt = _ctx.blogs.SingleOrDefault(c => c.blog_id == id);
            if (evt != null)
            {
                return View(evt);
            }
            evt = new blog();
            return View(evt);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Details(int id, HttpPostedFileBase uploadFile)
        {
            try
            {
                // TODO: Add update logic here
                // if (!IsAuthenticateAdmin())
                //   return RedirectToAction("LogOn", "AdminHome");
                var oldImage = string.Empty;
                var oldThumbImage = string.Empty;
                var blog = _ctx.blogs.SingleOrDefault(p => p.blog_id == id);
                if (uploadFile != null)
                {
                    if (blog != null && blog.blog_id > 0)
                    {
                        oldImage = blog.image_large;
                        oldThumbImage = blog.image_thumbnail;
                    }
                    var fileName = Path.GetFileName(uploadFile.FileName);
                    var sFileName = GenerateFileNameByNo(Request, Utilities.VirtualPath, fileName, DateTime.Now.ToString("yyyyMMddhhmmss"));
                    var filePath = Path.Combine(Request.MapPath(Utilities.VirtualPath), sFileName);
                    var fileThumbPath = Path.Combine(Request.MapPath(Utilities.VirtualPath + "Thumbs/"), sFileName);
                    ResizeImage(uploadFile.InputStream, fileThumbPath, 99, 99, true);
                    ResizeImage(uploadFile.InputStream, filePath, 400, 300, true);
                    if (blog != null)
                    {
                        blog.image_large = Utilities.PhysicalPath + sFileName;
                        blog.image_thumbnail = String.Format("{0}Thumbs/{1}", Utilities.PhysicalPath, sFileName);
                    }
                }
                UpdateModel(blog);
                _ctx.SaveChanges();

                DeleteFile(Request, Utilities.VirtualPath, oldImage);
                DeleteFile(Request, Utilities.VirtualPath + "Thumbs", oldThumbImage);

                ViewData["Msg"] = "Đã cập nhật!";
                return View(blog);
            }
            catch
            {
                ViewData["Msg"] = "Đã có lỗi xẩy ra. Vui lòng kiểm tra lại dữ liệu!";
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            // TODO: Add delete logic here
            //if (!IsAuthenticateAdmin())
            //    return RedirectToAction("LogOn", "AdminHome");
            if (id <= 0)
                return RedirectToAction("Create", "Manageblog", new blog());
            var blog = _ctx.blogs.SingleOrDefault(p => p.blog_id == id);
            _ctx.DeleteObject(blog);
            _ctx.SaveChanges();
            if (blog != null)
            {
                DeleteFile(Request, Utilities.VirtualPath, blog.image_large);
                DeleteFile(Request, Utilities.VirtualPath + "Thumbs", blog.image_thumbnail);
            }
            return RedirectToAction("Indexblogs");
        }

        public ActionResult Create()
        {
            var blog = new blog();
            return View(blog);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create([Bind(Exclude = "blog_id")]blog blog, HttpPostedFileBase uploadFile)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            try
            {
                if (uploadFile != null)
                {
                    var fileName = Path.GetFileName(uploadFile.FileName);
                    var sFileName = GenerateFileNameByNo(Request, Utilities.VirtualPath, fileName, DateTime.Now.ToString("yyyyMMddhhmmss"));
                    var filePath = Path.Combine(Request.MapPath(Utilities.VirtualPath), sFileName);
                    var fileThumbPath = Path.Combine(Request.MapPath(Utilities.VirtualPath + "Thumbs/"), sFileName);
                    ResizeImage(uploadFile.InputStream, fileThumbPath, 99, 99, true);
                    ResizeImage(uploadFile.InputStream, filePath, 400, 300, true);
                    blog.image_large = Utilities.PhysicalPath + sFileName;
                    blog.image_thumbnail = String.Format("{0}Thumbs/{1}", Utilities.PhysicalPath, sFileName);
                }
                blog.created_date = DateTime.Now;
                _ctx.AddToblogs(blog);
                _ctx.SaveChanges();
                ViewData["Msg"] = "Đã tạo thành công!";
                return RedirectToAction("Indexblogs");
            }
            catch
            {
                ViewData["Msg"] = "Đã có lỗi xẩy ra. Vui lòng kiểm tra lại dữ liệu!";
                return View(string.Empty);
            }
        }
    }
}
